package com.jabber.readers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class KillboardReader implements Runnable {

	private String host = "https://zkillboard.com/alliance/";
	private int lastKill = 0;

	private Document doc;

	private MultiUserChat multiuserChat;

	private static Logger logger = Logger.getLogger(KillboardReader.class);

	@Override
	public void run() {
		logger.info("Fleet-Up Thread Started");

		try {
			while (!Thread.currentThread().isInterrupted()) {
				logger.info("Parsing Killboard");
				parseKills();
				Thread.sleep(1000 * 60);
			}
		} catch (InterruptedException e) {
			logger.info("Thread interrupted... Shutting down?");
		} catch (IOException | XMPPException | NotConnectedException e) {
			logger.error(e.getMessage());
		}

	}

	public KillboardReader(Integer allianceKey, MultiUserChat multiUserChat)
			throws IOException {
		this.multiuserChat = multiUserChat;
		this.host = host + allianceKey;
		this.doc = Jsoup.connect(host).get();

		Elements elements = doc.select("tr[class=winwin killListRow]");
		Element element = elements.get(0);
		String value = element.attr("onclick");

		lastKill = getKillID(value);
		logger.info("Last Kill: " + lastKill);
	}

	private void parseKills() throws IOException, NotConnectedException,
			XMPPException {
		refreshDocument();

		List<Integer> killIDs = new ArrayList<Integer>();

		String query = "tr[class=winwin killListRow]";
		int x;

		String text;

		Elements elements = doc.select(query);
		for (Element element : elements) {
			text = element.attr("onclick");
			x = getKillID(text);

			if (x == lastKill)
				break;

			killIDs.add(x);
		}

		if (!killIDs.isEmpty()) {
			lastKill = killIDs.get(0);
			logger.info("Found " + killIDs.size() + " new kills.");
		}

		String kill;
		for (Integer killID : killIDs) {
			kill = parseKill(killID);
			multiuserChat.sendMessage(kill);
		}
	}

	private String parseKill(int killID) {
		String query = "tr[onclick=window.location='/kill/" + killID + "/']";

		Element element = doc.select(query).get(0);

		Elements elements = element.children();

		String text = elements.get(4).text();

		String ship = text.substring(text.indexOf('(') + 1, text.indexOf(')'));
		String victim = text.substring(0, text.indexOf('(') - 1);
		String victimGroup = text.substring(text.indexOf(')') + 2);

		text = elements.get(2).text();

		String system = text.substring(0, text.indexOf(' '));
		String secStatus = text.substring(text.indexOf(' ') + 1,
				text.indexOf(' ') + 4);
		String region = text.substring(text.indexOf(' ') + 5);

		text = elements.get(0).text();

		String time = text.substring(0, text.indexOf(' '));
		String worth = text.substring(text.indexOf(' ') + 1);

		text = elements.get(6).text();

		String finalBlow = text.substring(0, text.indexOf('(') - 1);
		String finalGroup = "";
		finalGroup = text.substring(text.indexOf(')') + 2);

		text = elements.get(1).child(0).attr("href");
		String link = "https://zkillboard.com";
		link = link + text;

		StringBuilder sb = new StringBuilder();
		sb.append(finalBlow);
		sb.append(" of ");
		sb.append(finalGroup);
		sb.append(" killed ");
		char c = ship.charAt(0);
		if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
			sb.append("an ");
		} else {
			sb.append("a ");
		}
		sb.append(ship);
		sb.append(" worth ");
		sb.append(worth);
		sb.append(" belonging to ");
		sb.append(victim);
		sb.append(" of ");
		sb.append(victimGroup);
		sb.append(" in ");
		sb.append(system);
		sb.append(" (");
		sb.append(secStatus);
		sb.append(") of ");
		sb.append(region);
		sb.append(" at ");
		sb.append(time);
		sb.append(" EVE Time. ");
		sb.append(link);

		return sb.toString();
	}

	private void refreshDocument() throws IOException {
		doc = Jsoup.connect(host).get();
	}

	private int getKillID(String text) {
		int begin = 23;
		int end = text.lastIndexOf("/'");

		return Integer.parseInt(text.substring(begin, end));
	}
}
